
<template>
  <div class="codeAssociated">
    <div>
      <pre class="previewhtml-main hljs">
              <code class="javascript">
      请先输入文件的绝对路径 路径地址大概为：E:/static 然后在赋值代码 代码是双向绑定的 输入地址即可
      上传文件需要 formidable包 操作方法如下
      npm install formidable

      前端请求为from格式提交文件
              </code>
          </pre>
    </div>
    <div class="tonyon_list">
      保存文件绝对路径的地址：
      <el-input size="small" v-model="url" placeholder style="width:50%;margin-left: 11px;"></el-input>
    </div>
    <el-button @click="shengcheng">生成代码</el-button>
    <el-tabs v-model="activeName" v-if="is_shengcheng" class="tables0e" style="line-height: 23px;">
      <el-tab-pane label="前端代码" name="0">
        <pre class="previewhtml-main hljs">
              <code class="javascript">
    //form提交

    {{html}}

    //uniapp案例

    uni.chooseImage({
		count: 6, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album', 'camera'], //从相册选择
		success: function(res) {
			const tempFilePaths = res.tempFilePaths;
                        // 多图上传
			tempFilePaths.forEach(s => {
				const uploadTask = uni.uploadFile({
					url: '请求地址' + '/filesUpload/add', //仅为示例，非真实的接口地址
					filePath: s,
					name: 'file',
					header: {
						'Content-Type': 'multipart/form-data' //记得设置
					},
					formData: {},
					success: uploadFileRes => {
                                            console.log(uploadFileRes)
					}
				});
			});
		}
	});

    
    // 其他格式的form自行百度
    //大致方式是
    //let formData = new FormData();
    // 向 formData 对象中添加文件
    //formData.append('file',this.file);
    //formData.append('file',this.file2);
              </code>
       </pre>
      </el-tab-pane>
      <el-tab-pane label="controller/filesUpload.js" name="1">
        <pre class="previewhtml-main hljs">
              <code class="javascript">
     let express = require('express');
     let router = express.Router();
     let filesUpload = require('../service/filesUpload.js')
     filesUpload = new filesUpload()

     /**
     * @api {post} /filesUpload/add 图片上传
     * @apiDescription ""
     */
     router.post('/add', async function (req, res, next) {
         let data = await filesUpload.add(req,res)
         res.send(data)
     });
     module.exports = router
              </code>
       </pre>
      </el-tab-pane>
      <el-tab-pane label="service/filesUpload.js" name="2">
        <pre class="previewhtml-main hljs">
              <code class="javascript">
    class filesUpload {
        constructor() {
        }
        emptyData(msg) {
            Object.keys(msg).map(s => {
                if (msg[s] === '' || msg[s] === undefined) {
                    delete msg[s]
                }
            })
            return msg
        }
        verify(test, val) {
            for (var item in test) {
                if (!val[test[item].name]) {
                    return test[item].name + "为空"
                }
            }
        }
        async add(req, res) {
            try {
                var data = {}
                var formidable = require('formidable')
                var form = new formidable.IncomingForm();
                form.uploadDir = "{{urlGo}}";
                form.keepExtensions = true;
                form.maxFieldsSize = 2 * 1024 * 1024; //限制大小
                form.multiples = true //多选
                await new Promise((prevct,err) => {
                    form.parse(req, function (error, fields, files) {
                        if (error) {
                            data = {
                                status: 501,
                                msg: "文件解析失败"
                            }
                            err(error)
                        } else {
                            var filesList = []
                            if (Object.prototype.toString.call(files.file) === '[object Array]') {
                                files.file.map(v => {
                                    filesList.push(uploadUrl(v.path))
                                })
                            } else {
                                filesList = uploadUrl(files.file.path)
                            }
                            data = {
                                status: 200,
                                data: filesList
                            }
                            prevct(filesList)
                        }
                    })
                })
                function uploadUrl(v) {
                    return v.match(/\upload(.+?)$/)[0]
                }
            } catch (error) {
              console.log(error)
                data = {
                    status: 500,
                    data: '未知错误'
                }
            }
            return data
        }
    }
    module.exports = filesUpload 
              </code>
       </pre>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import hljs from "highlight.js";
export default {
  name: "App",
  data() {
    return {
      activeName: "0",
      value: "",
      urlGo:"",
      url: "",
      is_shengcheng: false,
      html: `<form action="/filesUpload/add" method="post" enctype="multipart/form-data"></form>`,
      catalogue: "",
    };
  },
  watch: {
    activeName() {},
  },
  methods: {
    shengcheng() {
      this.is_shengcheng = false;
      this.urlGo = this.url.replace(/\\/g,'/')
      this.$nextTick(() => {
        this.is_shengcheng = true;
        this.$nextTick(() => {
          var pre = document.querySelectorAll(".previewhtml-main");
          Array.from(pre).map((v) => {
            hljs.highlightBlock(v);
          });
        });
      });
    },
  },
  async created() {},
  mounted() {
    this.$nextTick(() => {
      var pre = document.querySelectorAll(".previewhtml-main");
      Array.from(pre).map((v) => {
        hljs.highlightBlock(v);
      });
    });
  },
};
</script>
<style lang="scss" scoped="scoped">
.tonyon_list {
  width: 50%;
  display: inline-block;
  margin-top: 31px;
  margin-bottom: 31px;
}
</style>
